package permission

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/adminuserrole"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"strings"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserPwdLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 账号密码登录
func NewAdminUserPwdLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserPwdLoginLogic {
	return &AdminUserPwdLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserPwdLoginLogic) AdminUserPwdLogin(req *types.AdminUserLoginRequest) (resp *types.AdminUserLoginResponse, err error) {
	adminUserRoleDAO := permission.NewAdminUserRoleDao(l.ctx, l.svcCtx)
	adminRoleDAO := permission.NewAdminRoleDao(l.ctx, l.svcCtx)

	// 登录校验逻辑
	adminUser, err := l.LoginVerify(req)
	if err != nil {
		return nil, err
	}

	// 根据用户id查角色
	adminUserRoleConditions := make([]predicate.AdminUserRole, 0, 1)
	adminUserRoleConditions = append(adminUserRoleConditions, adminuserrole.AdminUserRoleUserIDEQ(int64(adminUser.ID)))
	adminUserRoles, err := adminUserRoleDAO.UserRoleConditionsAll(adminUserRoleConditions)
	if err != nil {
		if !ent.IsNotFound(err) {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户角色失败: %v", err.Error()))
		}
	}

	// 序列化角色id（角色id）
	roleIds := lo.Map(adminUserRoles, func(item *ent.AdminUserRole, _ int) int {
		return int(item.AdminUserRoleRoleID)
	})
	marshalRoleIds, _ := json.Marshal(roleIds)

	// 根据角色id查角色
	roleConditions := make([]predicate.AdminRole, 0, 1)
	roleConditions = append(roleConditions, adminrole.IDIn(roleIds...))
	adminRoles, err := adminRoleDAO.AdminRoleConditionsAll(roleConditions)
	if err != nil {
		if !ent.IsNotFound(err) {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户角色失败: %v", err.Error()))
		}
	}

	// 从角色中取出按钮id
	buttonOriginIds := lo.Map(adminRoles, func(item *ent.AdminRole, _ int) []int {
		return lo.Map(strings.Split(item.AdminRoleRouterIds, ","), func(item string, _ int) int {
			id, _ := strconv.Atoi(item)
			return id
		})
	})

	// 序列化按钮id（按钮id）
	allButtonIds := lo.Flatten(buttonOriginIds)
	buttonIds := lo.Uniq(allButtonIds)
	marshalButtonIds, _ := json.Marshal(buttonIds)

	// 生成token 参数：密钥，过期时间，用户id，角色id，按钮id
	jwtToken, err := common.JwtAdminCreate(l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, strconv.Itoa(adminUser.ID), string(marshalRoleIds), string(marshalButtonIds))
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerCommonError, fmt.Sprintf("生成token失败: %v", err.Error()))
	}
	// 生成rememberToken
	rememberToken, err := common.JwtAdminCreate(l.svcCtx.Config.Auth.AccessSecret, 60*60*24*7, strconv.Itoa(adminUser.ID), string(marshalRoleIds), string(marshalButtonIds))
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerCommonError, fmt.Sprintf("生成rememberToken失败: %v", err.Error()))
	}

	// 返回token
	return &types.AdminUserLoginResponse{
		Token:         jwtToken,
		RememberToken: rememberToken,
	}, nil
}

// LoginVerify - 登录验证逻辑
func (l *AdminUserPwdLoginLogic) LoginVerify(req *types.AdminUserLoginRequest) (*ent.AdminUser, error) {
	adminUserDAO := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	// 用base64Captcha库进行验证码校验
	verify := store.Verify(req.AccountLoginId, req.AccountLoginCode, true)
	if !verify {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminCaptchaError, "验证码错误")
	}

	// 根据用户名查用户
	conditions := make([]predicate.AdminUser, 0, 1)
	conditions = append(conditions, adminuser.AdminUserUsernameEQ(req.AccountLoginUsername))
	adminUser, err := adminUserDAO.AdminUserFirst(conditions)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, xerr.ErrCodeMsg(xerr.ServerAdminUserNotExist, "用户不存在")
		} else {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户失败: %v", err.Error()))
		}
	}

	// 用户名存在，但是状态为禁用
	if adminUser.AdminUserStatus != bizadmin.StatusOpen {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用")
	}

	// 用户名存在，但是已被删除
	if adminUser.IsDelete != bizadmin.NotDelete {
		adminUser.IsDelete = bizadmin.NotDelete
		adminUser.AdminUserStatus = bizadmin.StatusDisable
		_ = adminUserDAO.AdminUserUpdate(adminUser, nil)
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminAccountDeleted, "用户已被删除")
	}

	// 密码校验
	if !common.CheckPasswordHash(req.AccountLoginPassword, adminUser.AdminUserPassword) {
		return nil, xerr.ErrCodeMsg(xerr.ServerAdminPasswordError, "账号或密码错误")
	}

	return adminUser, nil
}
